import axios from './axios'
import store from '@/stores'
import Vue from 'vue'

export function getWxAuthorize (url) {
    // 获取微信授权地址
    let redirectUrl = url || window.location.href
    let wxCode = sessionStorage.getItem('wxCode')
    // code session处理授权返回死循环
    if (!wxCode) {
        axios.get(`/wechar/oauth2/qrCode?redirectUrl=${redirectUrl}`).then(data => {
            location.replace(data.data)
        }).catch(err => {
            Vue.prototype.$toast(err.message)
        })
    } else {
        location.replace(process.env.VUE_APP_PUBLIC_PATH)
    }
}

export function wxAuth (code, qrCode) {
    return new Promise(function (resolve, reject) {
        Vue.prototype.$loading()
        axios.post(`/wechar/oauth2/wecharCode`, {
            code: code
        }).then(data => {
            // 将code放置session处理授权返回死循环
            sessionStorage.setItem('wxCode', code)
            Vue.prototype.$ls.setItem('token', data.data.token)
            Vue.prototype.$loading(false)
            resolve(data)
        }).catch(err => {
            Vue.prototype.$toast(`wxAuth>>> ${err.message}`)
            reject(err)
        })
    })
}

// 获取微信签名信息
export function getWechatSignature () {
    //  恶心的坑 iOS在页面加载时只需签名一次且需要记录第一次的地址 后续签名都用该地址来签名
    var url = store.state.wechat.signUrl
    return new Promise(function (resolve, reject) {
        axios.post('/wechar/oauth2/wechatInfo', { url }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// 上传
export function upload (file, cb1) {
    let formData = new FormData()
    formData.append('file', file.file)
    return new Promise(function (resolve, reject) {
        axios({
            method: 'post',
            url: '/my/updateUserPic',
            data: formData
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// 坐标转换 百度坐标转高德
export function locationCoordinate (longitude, latitude) {
    return new Promise(function (resolve, reject) {
        axios.get(`https://restapi.amap.com/v3/assistant/coordinate/convert`, {
            noheaders: true,
            params: {
                coordsys: 'baidu', // 原坐标系，可选值：gps mapbar baidu autonavi(不进行转换)
                locations: `${longitude},${latitude}`,
                key: process.env.VUE_APP_GAODE_KEY
            }
        }).then(res => {
            let result = {
                longitude: longitude,
                latitude: latitude
            }
            if (res.status == '1') {
                let locations = res.locations.split(',')
                result.longitude = locations[0]
                result.latitude = locations[1]
            }
            resolve(result)
        }).catch(err => {
            reject(err)
        })
    })
}
